package com.yhgm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhgm.common.ErrorCode;
import com.yhgm.constant.CommonConstant;
import com.yhgm.constant.UserConstant;
import com.yhgm.exception.BusinessException;
import com.yhgm.mapper.DepartmentMapper;
import com.yhgm.mapper.PermissionsMapper;
import com.yhgm.model.dto.user.UserQueryRequest;
import com.yhgm.model.entity.Department;
import com.yhgm.model.entity.Permissions;
import com.yhgm.model.entity.Roles;
import com.yhgm.model.entity.User;
import com.yhgm.mapper.UserMapper;
import com.yhgm.model.enums.UserRoleEnum;
import com.yhgm.model.vo.LoginUserVO;
import com.yhgm.model.vo.UserVO;
import com.yhgm.service.DepartmentService;
import com.yhgm.service.RolesService;
import com.yhgm.service.UserService;
import com.yhgm.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Gaoming
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-03-22 21:32:01
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "yhgm";

    @Resource
    private RolesService rolesService;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private PermissionsMapper permissionsMapper;

    @Override
    public LoginUserVO userLogin(String username, String password, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(username, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (username.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (password.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("password", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, username cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return getLoginUserVO(user);
    }



    @Override
    public long userRegister(String username, String password, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(username, password, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (username.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (password.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!password.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (username.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
            // 3. 插入数据
            User user = new User();
            user.setUsername(username);
            user.setPassword(encryptPassword);
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        if (user.getDepartmentId() != null) {
            loginUserVO.setDepartmentName(departmentMapper.selectById(user.getDepartmentId()).getName());
        }
        if (user.getRoleId() != null) {
            loginUserVO.setRole(rolesService.getById(user.getRoleId()).getUserRole());
        }

        Long roleId = user.getRoleId();
        Roles roles = rolesService.getById(roleId);
        String ids = roles.getPermIds();
        List<Long> list = JSONUtil.toList(ids, Long.class);
        List<String> permList = new ArrayList<>();
        List<String> menuList = new ArrayList<>();
        for (Long aLong : list) {
            Permissions permissions = permissionsMapper.selectById(aLong);
            String code = permissions.getCode();
            Integer type = permissions.getType();
            if (type == 1) {
                menuList.add(code);
            } else {
                permList.add(code);
            }
        }
        loginUserVO.setPermList(permList);
        loginUserVO.setMenu(menuList);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        if (user.getDepartmentId() != null) {
            userVO.setDepartmentName(departmentMapper.selectById(user.getDepartmentId()).getName());
        }
        if (user.getRoleId() != null) {
            userVO.setRole(rolesService.getById(user.getRoleId()).getUserRole());
        }
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        List<UserVO> list = new ArrayList<>();
        for (User user : userList) {
            UserVO userVO = getUserVO(user);
            list.add(userVO);
        }
        return list;
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String name = userQueryRequest.getName();
        String profile = userQueryRequest.getProfile();
        Long roleId = userQueryRequest.getRoleId();
        Long departmentId = userQueryRequest.getDepartmentId();
        List<Department> allDepartments = new ArrayList<>();
        allDepartments.add(departmentMapper.selectById(departmentId));
        dfs(departmentId, allDepartments);
        List<Long> departmentIds = new ArrayList<>();
        for (Department department : allDepartments) {
            departmentIds.add(department.getId());
        }

        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(roleId != null, "roleId", roleId);
        queryWrapper.in("departmentId", departmentIds);
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.like(StringUtils.isNotBlank(profile), "profile", profile);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    private void dfs(Long parentId, List<Department> allDepartments) {
        // 查询当前部门的直接子部门
        List<Department> subDepartments = departmentMapper.selectList(new QueryWrapper<Department>().eq("pid", parentId));
        if (subDepartments != null && !subDepartments.isEmpty()) {
            // 将直接子部门加入结果列表
            allDepartments.addAll(subDepartments);
            // 递归查询子部门的子部门
            for (Department department : subDepartments) {
                dfs(department.getId(), allDepartments);
            }
        }
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    @Override
    public Integer updatePassword(Long id, String newPassword) {
        String hexPassword = DigestUtils.md5DigestAsHex((SALT + newPassword).getBytes());
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("password", hexPassword);
        Integer result = this.baseMapper.update(null, updateWrapper);
        return result;
    }
}




